/**
 * Created by ZT on 2018/7/5 0005.
 * node 启动的js，express作为中间件，连接数据库和前台
 */
const mysql = require('mysql');
const express = require('express');
const bodyParser = require('body-parser');
const ejs = require('ejs');
const ueditor = require('ueditor');
const jwt =require('jsonwebtoken');
const path = require('path');
const app = express();
app.use(bodyParser.json());
const jwtSecret = 'zt-secret';  //jwt密码
app.use(bodyParser.urlencoded({ extended: false }));
// view engine setup
app.engine('html', ejs.__express);
app.set('view engine', 'html');

app.set('views',path.join(__dirname,'../') +  path.normalize('src/backend/html'));




function setupCORS(req, res, next) {
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.header('Access-Control-Allow-Headers', 'X-Requested-With, Content-type,Accept,access_token,X-Key');
    res.header('Access-Control-Allow-Origin', '*');
    if (req.method === 'OPTIONS') {
        res.status(200).end();
    } else {
        next();
    }
}
app.all('/*', setupCORS);
app.disable('no cache');
app.use(function (req, res, next) {
    if(req.url.split('/')[1]=='api'){
        return next();
    }
   if(req.url.split('/')[1]=='back') {
       let token = req.header('access_token');
       console.log(4444);
       if (token && req.url.split('/')[2] != 'login') {
           jwt.verify(token, jwtSecret, (err, decoded) => {
               if (err) {
                   res.json({
                       ret: 0,
                       code:401,
                       msg: err.message,
                   })
               } else {
                   req._startTime = new Date(); // 获取时间 t1
                   var calResponseTime = function () {
                       var now = new Date(); //获取时间 t2
                       var deltaTime = now - req._startTime;

                       res.once('finish', calResponseTime);
                       res.once('close', calResponseTime);
                       req.url = '/'+req.url.split('/')[2];
                       return next();
                   }
                   req.url = '/'+req.url.split('/')[2];
                   return next();
               }
           });
       } else {
           req.url = '/'+req.url.split('/')[2];
           return next();
       }
   }else{
       req.url = '/'+req.url.split('/')[2];
       return next();
   }
});

const Login = require('../server/back/login');
app.use('/login',Login.loginPage);
app.use('/logout',Login.logout);
/****  
  *所有请求
 '/article'
 '/posts'
 '/delete'
 '/backGets'

 /photos
 /getPhotoById
 /api/add
 /savePhoto

 /getMessage'
 /postMessage

 /articlePersonal
 /getRight
***/

//-----------------------------------******后 台 文 章*********---------------------------------------------------------------
/**  getArticleData    获取文章
 * postArticle 文章添加
 * deleteArticle 删除文章
 * getArticle 获取文章标签，获取文章类别
 * getAritcleTag  文章标签
 * postArticleTag 更新与添加分类
 * deleteArticleKey删除分类
 *
 * getAritcleKey  关键字
 * deleteArticleKey
 * postArticleKey
 *
*/
const article  = require('../server/back/article');
/***公共请求   前后台需要获取文章数据* */
app.use('/article',article.getArticleData);
/***提交数据 文章**/
app.post('/BackPostArticle',article.postArticle);
/*删除文章*/
app.use('/delete',article.deleteArticle);
/* 获取文章标签，获取文章类别*/
app.use('/backGets',article.getArticle);
app.use('/getArticleTag',article.getAritcleTag);

app.use('/deleteArticleTag',article.deleteArticleTag);

app.use('/postArticleTag',article.postArticleTag);


app.use('/getArticleKey',article.getAritcleKey);

app.use('/deleteArticleKey',article.deleteArticleKey);

app.use('/postArticleKey',article.postArticleKey);



//------------------------------------********后 台 相 册**********------------------------------------------------------------
/**  execPhoto
 * getPhotoBySort
 * savePhoto
 * postPhoto
*/
const photos  = require('../server/back/photo');
//获取相册
app.use('/photos',photos.execPhoto); 
 //查找相册里面的照片
app.use('/getPhotoById',photos.getPhotoBySort);
/*** 后台请求,图片存储* */
var ueditorConfig = require('../static/ueditor/ueditor.config.json');//公共方
var dirName = path.resolve(__dirname, '..');
app.use('/api/add', ueditor(path.join(dirName, 'static'),photos.savePhoto));
/*相册添加*/
app.post('/savePhoto',photos.postPhoto);


//------------------------------------------*******前 台 留 言***********----------------------------------------------------------
/**  getMessage
 * postMessage
*/
const Message = require("../server/fro/message");
/*获取留言信息*/
app.use('/getMessage',Message.getMessage);
/*留言*/
app.post('/postMessage',Message.postMessage);
  



//----------------------------------------------*******前 台 文 章************------------------------------------------------------
/**articlePersonal
 * getRight
*/

const ArticleFro = require("../server/fro/article");

/*文章*/
app.use('/getArticles',ArticleFro.getArticles);

/*获取专栏信息  ---前台message=>articlePersonal*/
app.use('/articlePersonal',ArticleFro.articlePersonal);
/*获取右边固定的信息*/
app.use('/getRight',ArticleFro.getRight);

app.use('/articleTop',ArticleFro.getArticleTop);

app.use('/getUpAndDown',ArticleFro.getUpAndDown);

app.use('/getLinkContent',ArticleFro.getLinkContent);

app.use('/getSearchKey',ArticleFro.getSearchKey);

app.use('/likesThis',ArticleFro.likesThis);

//------------------------------*****前台留言*****---------------------------------
//getArticleMessage   //前台文章获取留言
//postArticleMessage  前台留言

app.use('/getArticleMessage',Message.getArticleInfoMessage);
Date.prototype.Format = function () { //author: zt
    let d = new Date();
    let times = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate() + ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds();
    return times;
};

app.use('/postArticleMessage',Message.postArticleInfoMessage);
Date.prototype.Format = function () { //author: zt
    let d = new Date();
    let times = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate() + ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds();
    return times;
};
/*-------------------获取相册类型 end----------------------*/

process.on('uncaughtException', function (err) {
    console.log('Caught exception: ' + err);
    process.exit(1);
})

    var server = app.listen(8081, '127.0.0.1', function () {
    var host = server.address().address;
    var port = server.address().port;
    console.log(host, port);
    console.log(35555);
});
